package com.work.yshop.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.work.yshop.R;
import com.work.yshop.databinding.FragmentProfileBinding;
import com.work.yshop.model.CartItem;
import com.work.yshop.model.Favorite;
import com.work.yshop.model.Order;
import com.work.yshop.model.ProductHistory;
import com.work.yshop.mvp.contract.UserDataContract;
import com.work.yshop.mvp.presenter.UserDataPresenter;
import com.work.yshop.ui.activity.CartActivity;
import com.work.yshop.ui.activity.FavoriteActivity;
import com.work.yshop.ui.activity.HistoryActivity;
import com.work.yshop.ui.activity.LoginActivity;
import com.work.yshop.ui.activity.OrderListActivity;
import com.work.yshop.ui.activity.SellerHomeActivity;
import com.work.yshop.ui.activity.SettingsActivity;
import com.work.yshop.utils.UserSession;

import java.util.List;

/**
 * 个人中心Fragment
 */
public class ProfileFragment extends Fragment implements UserDataContract.View {

    private FragmentProfileBinding binding;
    private UserDataPresenter presenter;

    public static ProfileFragment newInstance() {
        return new ProfileFragment();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = FragmentProfileBinding.inflate(inflater, container, false);
        return binding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        
        // 初始化Presenter
        presenter = new UserDataPresenter(requireContext());
        presenter.attachView(this);
        
        // 初始化数据
        initData();
        // 设置监听器
        setupListeners();
        
        // 加载购物车、订单、收藏和浏览历史数据
        presenter.loadCartItems();
        presenter.loadOrderList();
        presenter.loadFavoriteList();
        presenter.loadHistoryList();
    }

    /**
     * 初始化数据
     */
    private void initData() {
        // 模拟用户数据
        binding.tvUsername.setText("153****3361");
        binding.tvUserRole.setText("普通用户");
        
        // 模拟资产数据
        binding.tvBalance.setText("0");
        binding.tvRedPacket.setText("0.00");
        binding.tvPoints.setText("52");
    }

    /**
     * 设置监听器
     */
    private void setupListeners() {
        // 查看全部资产
        binding.tvViewAll.setOnClickListener(v -> 
                showToast("暂未开放此功能"));
        
        // 优惠券
        binding.layoutCoupons.setOnClickListener(v -> 
                showToast("暂无优惠券"));
        
        // 礼品卡
        binding.layoutGiftCard.setOnClickListener(v -> 
                showToast("暂无礼品卡"));
        
        // 积分商城
        binding.layoutPointsMall.setOnClickListener(v -> 
                showToast("积分商城暂未开放"));
        
        // 订单相关
        binding.tvAllOrders.setOnClickListener(v -> 
                navigateToOrderList(0));
        
        binding.layoutToPay.setOnClickListener(v -> 
                navigateToOrderList(1));
        
        binding.layoutToShip.setOnClickListener(v -> 
                navigateToOrderList(2));
        
        binding.layoutToReceive.setOnClickListener(v -> 
                navigateToOrderList(3));
        
        binding.layoutToReview.setOnClickListener(v -> 
                navigateToOrderList(4));
        
        binding.layoutAfterSale.setOnClickListener(v -> 
                showToast("查看退款/售后"));
        
        // 功能菜单
        binding.menuShoppingCart.setOnClickListener(v -> 
                navigateToCart());
        
        binding.menuFavorites.setOnClickListener(v -> 
                navigateToFavorites());
        
        binding.menuHistory.setOnClickListener(v -> 
                navigateToHistory());
        
        // 我要开店
        binding.menuOpenShop.setOnClickListener(v -> {
            Intent intent = new Intent(getActivity(), SellerHomeActivity.class);
            startActivity(intent);
        });
        
        // 联系客服
        binding.menuCustomerService.setOnClickListener(v -> 
                showToast("联系客服功能暂未开放"));
        
        // 设置
        binding.menuSettings.setOnClickListener(v -> {
            Intent intent = new Intent(getActivity(), SettingsActivity.class);
            startActivity(intent);
        });
        
        // 关于我们
        binding.menuAboutUs.setOnClickListener(v -> 
                showToast("关于我们功能暂未开放"));
        
        // 隐私政策
        binding.menuPrivacyPolicy.setOnClickListener(v -> 
                showToast("隐私政策功能暂未开放"));
        
        // 退出登录
        binding.menuLogout.setOnClickListener(v -> 
                showLogoutConfirmDialog());
    }
    
    /**
     * 跳转到订单列表页面
     * @param tabIndex 订单状态对应的标签索引
     */
    private void navigateToOrderList(int tabIndex) {
        Intent intent = new Intent(getActivity(), OrderListActivity.class);
        intent.putExtra("tab_index", tabIndex);
        startActivity(intent);
    }
    
    /**
     * 跳转到购物车页面
     */
    private void navigateToCart() {
        try {
            Intent intent = new Intent(getActivity(), CartActivity.class);
            startActivity(intent);
        } catch (Exception e) {
            showToast("购物车功能即将上线");
        }
    }
    
    /**
     * 跳转到收藏页面
     */
    private void navigateToFavorites() {
        try {
            Intent intent = new Intent(getActivity(), FavoriteActivity.class);
            startActivity(intent);
        } catch (Exception e) {
            showToast("收藏功能即将上线");
        }
    }
    
    /**
     * 跳转到浏览历史页面
     */
    private void navigateToHistory() {
        try {
            Intent intent = new Intent(getActivity(), HistoryActivity.class);
            startActivity(intent);
        } catch (Exception e) {
            showToast("浏览历史功能即将上线");
        }
    }
    
    /**
     * 显示Toast提示
     */
    private void showToast(String message) {
        Toast.makeText(getContext(), message, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (presenter != null) {
            presenter.detachView();
        }
        binding = null;
    }
    
    // UserDataContract.View接口实现
    @Override
    public void showLoading() {
        // 在个人中心页面不需要显示加载中
    }

    @Override
    public void hideLoading() {
        // 在个人中心页面不需要隐藏加载中
    }

    @Override
    public void showError(String message) {
        showToast(message);
    }

    @Override
    public void showHistoryList(List<ProductHistory> historyList) {
        // 获取实际的历史记录商品数量
        int historyCount = historyList.size();
        
        // 更新足迹菜单文本，显示足迹数量
        TextView tvHistory = binding.menuHistory.findViewById(android.R.id.text1);
        if (tvHistory != null) {
            tvHistory.setText(getString(R.string.history) + "(" + historyCount + ")");
        } else {
            // 找不到TextView，尝试在第一个子View中查找
            for (int i = 0; i < binding.menuHistory.getChildCount(); i++) {
                View child = binding.menuHistory.getChildAt(i);
                if (child instanceof TextView) {
                    ((TextView) child).setText(getString(R.string.history) + "(" + historyCount + ")");
                    break;
                }
            }
        }
        
        // 在控制台打印日志
        System.out.println("浏览历史数量: " + historyCount);
    }

    @Override
    public void showFavoriteList(List<Favorite> favoriteList) {
        // 获取实际的收藏商品数量
        int favoriteCount = favoriteList.size();
        
        // 更新收藏菜单文本，显示收藏数量
        TextView tvFavorites = binding.menuFavorites.findViewById(android.R.id.text1);
        if (tvFavorites != null) {
            tvFavorites.setText(getString(R.string.favorites) + "(" + favoriteCount + ")");
        } else {
            // 找不到TextView，尝试在第一个子View中查找
            for (int i = 0; i < binding.menuFavorites.getChildCount(); i++) {
                View child = binding.menuFavorites.getChildAt(i);
                if (child instanceof TextView) {
                    ((TextView) child).setText(getString(R.string.favorites) + "(" + favoriteCount + ")");
                    break;
                }
            }
        }
        
        // 在控制台打印日志
        System.out.println("收藏数量: " + favoriteCount);
    }

    @Override
    public void showCartItems(List<CartItem> cartItems) {
        // 更新购物车数量，计算所有商品的总数量
        int cartCount = 0;
        for (CartItem item : cartItems) {
            cartCount += item.getQuantity();
        }
        
        // 更新购物车菜单文本，显示商品数量
        TextView tvShoppingCart = binding.menuShoppingCart.findViewById(android.R.id.text1);
        if (tvShoppingCart != null) {
            tvShoppingCart.setText(getString(R.string.shopping_cart) + "(" + cartCount + ")");
        } else {
            // 找不到TextView，尝试在第一个子View中查找
            for (int i = 0; i < binding.menuShoppingCart.getChildCount(); i++) {
                View child = binding.menuShoppingCart.getChildAt(i);
                if (child instanceof TextView) {
                    ((TextView) child).setText(getString(R.string.shopping_cart) + "(" + cartCount + ")");
                    break;
                }
            }
        }
        
        // 在控制台打印日志
        System.out.println("购物车数量: " + cartCount);
    }

    @Override
    public void showOrderList(List<Order> orderList) {
        // 统计各种状态的订单数量
        int pendingCount = 0;
        int processingCount = 0;
        int shippedCount = 0;
        int completedCount = 0;
        
        for (Order order : orderList) {
            switch (order.getStatus()) {
                case Order.STATUS_PENDING:
                    pendingCount++;
                    break;
                case Order.STATUS_PROCESSING:
                    processingCount++;
                    break;
                case Order.STATUS_SHIPPED:
                    shippedCount++;
                    break;
                case Order.STATUS_COMPLETED:
                    completedCount++;
                    break;
            }
        }
        
        // 更新订单状态数量显示
        // 待付款
        updateOrderBadge(binding.layoutToPay, pendingCount);
        
        // 待发货
        updateOrderBadge(binding.layoutToShip, processingCount);
        
        // 待收货
        updateOrderBadge(binding.layoutToReceive, shippedCount);
        
        // 待评价
        updateOrderBadge(binding.layoutToReview, completedCount);
        
        // 在控制台打印日志
        System.out.println("待付款订单: " + pendingCount);
        System.out.println("待发货订单: " + processingCount);
        System.out.println("待收货订单: " + shippedCount);
        System.out.println("已完成订单: " + completedCount);
    }
    
    /**
     * 更新订单状态角标
     * @param layout 订单状态布局
     * @param count 数量
     */
    private void updateOrderBadge(ViewGroup layout, int count) {
        if (layout == null) return;
        
        // 查找布局中的TextView角标
        TextView badge = null;
        try {
            // 查找FrameLayout，然后找到其中的TextView
            for (int i = 0; i < layout.getChildCount(); i++) {
                View child = layout.getChildAt(i);
                if (child instanceof FrameLayout) {
                    FrameLayout frameLayout = (FrameLayout) child;
                    for (int j = 0; j < frameLayout.getChildCount(); j++) {
                        View frameChild = frameLayout.getChildAt(j);
                        if (frameChild instanceof TextView) {
                            badge = (TextView) frameChild;
                            break;
                        }
                    }
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        // 更新角标
        if (badge != null) {
            if (count > 0) {
                badge.setVisibility(View.VISIBLE);
                badge.setText(String.valueOf(count));
            } else {
                badge.setVisibility(View.GONE);
            }
        }
    }

    @Override
    public void showEmptyView(int type) {
        // 在个人中心页面不需要显示空视图
    }

    @Override
    public void showResult(boolean success, String message) {
        if (!success) {
            showToast(message);
        }
    }

    /**
     * 显示退出登录确认对话框
     */
    private void showLogoutConfirmDialog() {
        androidx.appcompat.app.AlertDialog.Builder builder = new androidx.appcompat.app.AlertDialog.Builder(requireContext());
        builder.setTitle("退出登录")
               .setMessage("确定要退出登录吗？")
               .setPositiveButton("确定", (dialog, which) -> {
                   logout();
               })
               .setNegativeButton("取消", null)
               .show();
    }
    
    /**
     * 退出登录
     */
    private void logout() {
        // 清除用户会话信息
        UserSession.getInstance().clear();
        
        // 显示退出成功提示
        showToast("已退出登录");
        
        // 跳转到登录页面
        Intent intent = new Intent(getActivity(), LoginActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);
        
        // 关闭当前Activity
        if (getActivity() != null) {
            getActivity().finish();
        }
    }
} 